package fms.service;

import fms.thread.FlightPlanDataThread;
import fms.thread.Grid2BySkyviewDataThread;
import fms.util.ConfUtil;
import fms.util.FtpParamVo;
import fms.util.ObjectUtil;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * To change this template use File | Settings | File Templates.
 */
public class CptInfoDataStoreService {
    private static Logger logger = Logger.getLogger(CptInfoDataStoreService.class);
    private static final String AccessMethodFtp = "FTP";
    private static final String AccessMethodLocal = "LOCAL";

    /**
     * delete from cpt_info;
     * delete from plan_cpt_wd;
     * delete from grib2_wd_info;
     * 解析飞行计划，grid2数据的主入口
     */
    public static void main(String[] args) {
        String logFilePath= ConfUtil.props.getProperty("log4jconfig");
        PropertyConfigurator.configure(logFilePath);
        logger.info("飞行计划和grid2数据解析服务V1.0.1已启动！");

        File fBaseParam = new File(ConfUtil.props.getProperty("baseParamFilePath"));
        final SAXReader readerBaseParam = new SAXReader();

        //航班计划数据存放路径
        String scanDirPath = "";
        //航班计划数据备份路径
        String backupDirPath = "";

        //grib2数据存放路径
        String grib2DirPath = "";
        //grib2数据备份路径
        String backupGrib2DirPath = "";

        // Skyview项目中所使用的解析后的grib2数据文件存放路径
        String grib2BySkyviewDirPath = "";
        // Skyviewgrib2数据备份路径
        String backupGrib2BySkyviewDirPath = "";

        Map<String, String> mapAirlinesCodes = new HashMap<String, String>();

        try {
            final Document paraseRuleDoc = readerBaseParam.read(fBaseParam);
            Element uniqueObject = (Element) paraseRuleDoc.selectSingleNode("/baseParamter/windTempInterfaceService/scanDir");
            scanDirPath = uniqueObject.getText();
            uniqueObject = (Element) paraseRuleDoc.selectSingleNode("/baseParamter/windTempInterfaceService/backupDir");
            backupDirPath = uniqueObject.getText();

            //解析grid2数据成功后的备份文件路径
            uniqueObject=(Element)paraseRuleDoc.selectSingleNode("/baseParamter/windTempInterfaceService/backupGrib2SuccessDir");
            String backupGrib2SuccessDir=uniqueObject.getText();

            //解析飞行计划成功后的备份路径
            uniqueObject=(Element)paraseRuleDoc.selectSingleNode("/baseParamter/windTempInterfaceService/backupSuccessDir");
            String backupPlanSuccessData = uniqueObject.getText();

            uniqueObject = (Element) paraseRuleDoc.selectSingleNode("/baseParamter/windTempInterfaceService/jetplanAccessMethod");
            String accessMethod = uniqueObject.getText();

            FtpParamVo ftpParamVo = new FtpParamVo();
            if ( (null != accessMethod) && (accessMethod.equals(AccessMethodFtp)) ) {
                ftpParamVo.setIp( uniqueObject.attributeValue("ip") );
//System.out.println(uniqueObject.attributeValue("ip"));
                ftpParamVo.setUserName( uniqueObject.attributeValue("username") );
                ftpParamVo.setPassWord( uniqueObject.attributeValue("passwd") );
                ftpParamVo.setPort( Integer.valueOf(uniqueObject.attributeValue("port")) );
//                ftpParamVo.setPath( uniqueObject.attributeValue("path") );
//System.out.println(" ftpParamVo.getPath():" + ftpParamVo.getPath());
            }

            uniqueObject = (Element) paraseRuleDoc.selectSingleNode("/baseParamter/windTempInterfaceService/grib2Dir");
            grib2DirPath = uniqueObject.getText();
            uniqueObject = (Element) paraseRuleDoc.selectSingleNode("/baseParamter/windTempInterfaceService/backupGrib2Dir");
            backupGrib2DirPath = uniqueObject.getText();

            uniqueObject = (Element) paraseRuleDoc.selectSingleNode("/baseParamter/windTempInterfaceService/grib2BySkyviewWindInfoDir");
            grib2BySkyviewDirPath = uniqueObject.getText();
            uniqueObject = (Element) paraseRuleDoc.selectSingleNode("/baseParamter/windTempInterfaceService/backupGrib2BySkyviewDir");
            backupGrib2BySkyviewDirPath = uniqueObject.getText();
            //解析SKYVIEW格式的Grib2数据成功后的备份路径
            uniqueObject=(Element)paraseRuleDoc.selectSingleNode("/baseParamter/windTempInterfaceService/backupGrib2BySkyviewSuccessDir");
            String backupGrib2SuccessData=uniqueObject.getText();

            File fParseRule = null;
            fParseRule = new java.io.File(ConfUtil.props.getProperty("parseRuleFilePath"));
            final SAXReader reader = new SAXReader();
            try {
                logger.info("（DataStoreService）航空公司三字码和二字码对照表加载中！");
                final Document paraseRulenDoc = reader.read(fParseRule);
                List airlineCodeList = paraseRulenDoc.selectNodes("/FPLParseRules/TxtplanParseRule/AirlinesFlags/AirlineCode");
                Iterator it = airlineCodeList.iterator();
                while (it.hasNext()) {
                    Element airlinesCode = (Element) it.next();
                    mapAirlinesCodes.put(airlinesCode.attributeValue("id"), airlinesCode.getTextTrim());
                }
                logger.info("（DataStoreService）航空公司三字码和二字码对照表加载结束！");
            } catch (final Exception e) {
                logger.error(e.getMessage());
            }

            // 飞行计划主线程
            FlightPlanDataThread flayPlanThread = null;
            if (!ObjectUtil.isBlank(accessMethod)
                    && accessMethod.equals(AccessMethodFtp)) {
                flayPlanThread = new FlightPlanDataThread(scanDirPath, backupDirPath,
                        backupPlanSuccessData, AccessMethodFtp, ftpParamVo,mapAirlinesCodes);
            } else if (!ObjectUtil.isBlank(accessMethod)
                    && accessMethod.equals(AccessMethodLocal)) {
                flayPlanThread = new FlightPlanDataThread(scanDirPath, backupDirPath,
                        backupPlanSuccessData, AccessMethodLocal, ftpParamVo,mapAirlinesCodes);
            }
            // grib2数据主线程（由于，我们无法获取到气象局的Grib2接口，所以，将其注释；若使用先看看其是否具备“去重，再插入功能”）
//            Grid2DataThread grid2DataThread = new Grid2DataThread(grib2DirPath, backupGrib2DirPath, backupGrib2SuccessDir);

            // skyview格式的Grib2数据主线程
            Grid2BySkyviewDataThread grid2BySkyviewDataThread = new Grid2BySkyviewDataThread(grib2BySkyviewDirPath,
                    backupGrib2BySkyviewDirPath, backupGrib2SuccessData);

            //构造一个ScheduledThreadPoolExecutor对象，并且设置它的容量为3个
            ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(3);

            // 隔2秒后开始执行任务，几乎是每5秒执行一次
            stpe.scheduleWithFixedDelay(flayPlanThread, 2, 5, TimeUnit.SECONDS);

            // 隔2秒后开始执行任务，并且在上一次任务执行完成后隔2秒再执行一次；
//            stpe.scheduleWithFixedDelay(grid2DataThread, 0, 20, TimeUnit.SECONDS);

            // 隔0分钟后开始执行任务，并且在上一次任务执行完成后隔10分钟再执行一次（尽量释放内存）；
            stpe.scheduleWithFixedDelay(grid2BySkyviewDataThread, 0, 10, TimeUnit.MINUTES);
        } catch (final Exception e) {
            logger.error("程序异常终止：" + e.getMessage());
        }
    }
}